package com.aiwiown.snackmq.broker.handler.console;

import com.aiwiown.snackmq.broker.auth.AuthorizationService;
import com.aiwiown.snackmq.cluster.metadata.MetadataManager;
import com.aiwiown.snackmq.common.dto.console.RoleInfoDTO;
import com.aiwiown.snackmq.common.handler.RequestContext;
import com.aiwiown.snackmq.common.message.Message;
import com.aiwiown.snackmq.common.message.MessageStatus;
import com.aiwiown.snackmq.common.message.MessageType;
import com.aiwiown.snackmq.common.serialization.JsonSerializer;
import com.aiwiown.snackmq.common.serialization.SerializerFactory;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ListRolesHandler extends AbstractLeaderRequiredConsoleHandler {

    private final JsonSerializer serializer = SerializerFactory.getJsonSerializer();

    public ListRolesHandler(MetadataManager metadataManager, AuthorizationService authorizationService) {
        super(metadataManager, authorizationService);
    }

    @Override
    public MessageType getMessageType() {
        return MessageType.LIST_ROLES_REQUEST;
    }

    @Override
    protected void doHandle(RequestContext ctx, Message request) {
        try {
            java.util.List<RoleInfoDTO> roles = metadataManager.getAllRolePermissions().entrySet().stream()
                    .map(entry -> new RoleInfoDTO(entry.getKey(), entry.getValue()))
                    .collect(java.util.stream.Collectors.toList());

            Message response = Message.builder()
                    .messageId(request.getMessageId())
                    .type(MessageType.RESPONSE)
                    .status(MessageStatus.SUCCESS)
                    .body(serializer.serialize(roles))
                    .build();
            ctx.writeResponse(response);
        } catch (Exception e) {
            log.warn("Failed to list roles: {}", e.getMessage());
            Message errorResponse = Message.builder()
                    .messageId(request.getMessageId())
                    .type(MessageType.RESPONSE)
                    .status(MessageStatus.FAILED)
                    .errorMessage(e.getMessage())
                    .build();
            ctx.writeResponse(errorResponse);
        }
    }
}